import util from '@/common/util.js';
import {
	updateCarInfo
} from '@/api/request.js';
// 管理账号信息
const USERS_KEY = 'USERS_KEY';

const ER_KEY = 'ER_KEY';

// 管理账号信息
const WX_KEY = 'WX_KEY';

let timer = ""; //定时器

const getUsers = function() {
	let ret = '';
	ret = uni.getStorageSync(USERS_KEY);
	if (!ret) {
		ret = '{}';
	}
	return JSON.parse(ret);
}

const addUser = function(userInfo) {
	let users = getUsers();
	if (userInfo) {
		users = {
			user: userInfo
		};
	}
	uni.setStorageSync(USERS_KEY, JSON.stringify(users));
}

//登出 清理本地缓存的token和user对象
const logOut = function(userInfo) {
	
	uni.clearStorageSync() //wos
	uni.removeStorage({
		key: USERS_KEY,
		success: function(res) {
			console.log('logout success');
		}
	});
}

const geWxInfo = function() {
	let ret = '';
	ret = uni.getStorageSync(WX_KEY);
	
	if (!ret) {
		ret = '{}';
	}
	return JSON.parse(ret);
}

const addWxinfo = function(wxInfo) {
	let wxs = geWxInfo();
	if (wxInfo) {
		wxs = {
			wx: wxInfo.wx
		};
	}
	uni.setStorageSync(WX_KEY, JSON.stringify(wxs));
}
//登出 清理本地缓存的wx 信息对象
const logOutWx = function(wxinfo) {
	uni.removeStorage({
		key: WX_KEY,
		success: function(res) {
			console.log('logout success');
		}
	});
}

//获取全局token
const getToken = function(userInfo) {
	let ret = '';
	// console.log(uni.getStorageSync(USERS_KEY));
	ret = uni.getStorageSync(USERS_KEY);
	let token = '';
	if (ret) {
		token = JSON.parse(ret).cre_token;
	}
	return token;
}

//获取位置
const getposition = function(carId, taskId) {
	uni.authorize({
		scope: 'scope.userLocation', // 获取地理信息必填的参数，其它参数见文档
		success(res) {
			timer = setInterval(() => {
				uni.getLocation({
					type: 'gcj02', // <map> 组件默认为国测局坐标gcj02
					altitude: true,
					success(res) {
						let param = {
							"carId": carId,
							"taskId": taskId,
							"lng": res.longitude,
							"lat": res.latitude
						}
						console.log(param);
						updateCarInfo(param).then(res => {
							if (res.code == 200) {
								console.log("上传经纬度成功")
							} else {
								uni.showModal({
									title: '警告',
									content: 'code不符 请联系管理员',
									showCancel: false
								})
							}
						}).catch(err => {
							uni.showModal({
								title: '警告',
								content: '失败',
								showCancel: false
							})
						})
					}
				})
			}, 60000) //一分钟执行一次、
		},
		// 授权失败
		fail(err) {
			err = err['errMsg']
			uni.showModal({
				title: '温馨提示',
				content: '请在设置里配置位置授权，您必须授权!',
				showCancel: false,
				confirmText: '确认'
			})

		}
	})
}

//结束定时器
const endposition = function() {
	clearInterval(timer);
}
export default {
	getUsers,
	addUser,
	getToken,
	logOut,
	geWxInfo,
	addWxinfo,
	logOutWx,
	getposition,
	endposition
}
